package com.stephen.redisdemo.sparsearray;

/**
 * 稀疏数组的创建与恢复
 */
public class SparseArray {

    public static void main(String[] args) {
        int[][] chess = new int[11][12];
        System.out.println(chess.length); // 行数
        System.out.println(chess[0].length); // 列数
        chess[1][2] = 1;
        chess[2][3] = 2;

        // 非0值的个数
        int sum = 0;

        for(int[] row: chess) {
            for(int data : row) {
                System.out.printf("%d\t",data);
                if (data != 0) {
                    sum ++;
                }
            }
            System.out.println();
        }

        System.out.println("sum = " + sum);

        System.out.println("稀疏数组------");

        // 固定3列,行数比真实数据个数多一行,记录总的行数,列数,数据总个数
        int[][] spareArr = new int[sum + 1][3];

        // 给稀疏数组第一行赋值
        spareArr[0][0] = chess.length;
        spareArr[0][1] = chess[0].length;
        spareArr[0][2] = sum;

        int count = 0; // 记录是第几个非0数据
        for (int i = 0; i < chess.length; i++) {
            for(int j = 0; j < chess[0].length; j++) {
                if (chess[i][j] != 0) {
                    count ++ ;
                    spareArr[count][0] = i;
                    spareArr[count][1] = j;
                    spareArr[count][2] = chess[i][j];
                }
            }
        }
        System.out.println("遍历稀疏数组-----");
        for (int i = 0; i < spareArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n",spareArr[i][0],spareArr[i][1],spareArr[i][2]);
        }

        System.out.println("稀疏数组 恢复成 二维数组-----");
        // 定义新数组
        int[][] newArr = new int[spareArr[0][0]][spareArr[0][1]];
        System.out.println("newArr length: " + newArr.length);
        System.out.println("newArr column: " + newArr[0].length);

        // 给新数组赋值
        for (int i = 1; i < spareArr.length;i++){
            newArr[spareArr[i][0]][spareArr[i][1]] = spareArr[i][2];
        }

        System.out.println("打印新的二维数组----");

        for (int[] row : newArr) {
            for (int data : row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }


    }

}
